import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

class Solution {
    List<List<Integer>> res;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        res=new LinkedList<>();
        LinkedList<Integer> path=new LinkedList<>();
        Arrays.sort(candidates);
        backtrack(candidates,0,target,0,path);
        return res;
    }

    void backtrack(int[] candidates,int begin,int target,int sum,LinkedList<Integer> path){
        if (sum > target) {
            return;
        }
        if(sum==target){
            res.add(new LinkedList<>(path));
            return;
        }
        for(int i=begin;i<candidates.length&&candidates[i]+sum<=target;i++){
            path.add(candidates[i]);
            sum+=candidates[i];
            backtrack(candidates,i,target,sum,path);
            path.removeLast();
            sum-=candidates[i];
        }
    }
}